package com.lxx.codegen.mbgplugins;

import java.util.List;

import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.PluginAdapter;
import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;
import org.mybatis.generator.api.dom.java.Interface;
import org.mybatis.generator.api.dom.java.JavaVisibility;
import org.mybatis.generator.api.dom.java.Method;
import org.mybatis.generator.api.dom.java.Parameter;
import org.mybatis.generator.api.dom.java.TopLevelClass;
import org.mybatis.generator.api.dom.xml.Attribute;
import org.mybatis.generator.api.dom.xml.Document;
import org.mybatis.generator.api.dom.xml.TextElement;
import org.mybatis.generator.api.dom.xml.XmlElement;

public class DeleteLogicPlugin extends PluginAdapter {

	@Override
	public boolean validate(List<String> warnings) {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	public boolean clientGenerated(Interface interfaze,
			TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
		Method m = new Method("deleteLogicByIds");

		m.setVisibility(JavaVisibility.PUBLIC);

		m.setReturnType(FullyQualifiedJavaType.getIntInstance());

		m.addParameter(new Parameter(FullyQualifiedJavaType.getIntInstance(),
				"deleteFlag", "@Param(\"deleteFlag\")"));
		m.addParameter(new Parameter(new FullyQualifiedJavaType("Integer[]"),
				"ids", "@Param(\"ids\")"));

		context.getCommentGenerator().addGeneralMethodComment(m,
				introspectedTable);
//		topLevelClass.addMethod(m);
		interfaze.addMethod(m);
		interfaze.addImportedType(new FullyQualifiedJavaType("org.apache.ibatis.annotations.Param"));
		return true;
	}
	
	@Override
	public boolean sqlMapDocumentGenerated(Document document, IntrospectedTable introspectedTable) {
		
		String tableName = introspectedTable.getAliasedFullyQualifiedTableNameAtRuntime();//数据库表名  
		
		XmlElement parentElement = document.getRootElement();

		// 产生分页语句前半部分
		XmlElement deleteLogicByIdsElement = new XmlElement("update");
		deleteLogicByIdsElement.addAttribute(new Attribute("id", "deleteLogicByIds"));
		
		deleteLogicByIdsElement.addElement(
				new TextElement(
				"update " + tableName + " set deleteFlag = #{deleteFlag,jdbcType=INTEGER} where id in "
				+ " <foreach item=\"item\" index=\"index\" collection=\"ids\" open=\"(\" separator=\",\" close=\")\">#{item}</foreach> "
				));
		
		parentElement.addElement(deleteLogicByIdsElement);

		return super.sqlMapDocumentGenerated(document, introspectedTable);
	}

}
